package com.http.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import lombok.Cleanup;

/**
 * @author litong
 * @date 2018年6月4日_下午3:55:26 
 * @version 1.0 
 */
public class HttpPostExample {
	public static void main(String[] args) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://www.baidu.com");

		List<NameValuePair> params = new ArrayList<>();
		params.add(new BasicNameValuePair("litong", "123"));

		HttpEntity httpEntity = null;
		try {
			httpEntity = new UrlEncodedFormEntity(params);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		httpPost.setEntity(httpEntity);

		CloseableHttpResponse httpResponse = null;
		try {
			httpResponse = httpClient.execute(httpPost);
		} catch (IOException e) {
			e.printStackTrace();
		}

		InputStream content=null;
		try {
			content = httpResponse.getEntity().getContent();
		} catch (UnsupportedOperationException | IOException e) {
			e.printStackTrace();
		}
		try {
			@Cleanup BufferedReader bufReader = new BufferedReader(new InputStreamReader(content));
			String line=null;
			while((line=bufReader.readLine())!=null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
